﻿using LockerRack.Exceptions;
using LockerRack.Interfaces;
using Microsoft.Practices.Unity;
using TasksLib.DrawerStuff;

namespace TasksLib.Resolvers
{
    public class TaskFileResolver : IDrawerFileResolver
    {
        public const string TASK_TYPE = "task";
        public const string UNKNOWN_TYPE = "unknown";

        public IUnityContainer Container { get; private set; }

        public TaskFileResolver()
        {
            var container = new UnityContainer();
            container.RegisterType<IDrawerFileResolver, TaskFileResolver>();
            container.RegisterType<IDrawerFileStuff, TaskXmlFile>(TASK_TYPE);
            container.RegisterType<IDrawerFileStuff, UnknownFile>(UNKNOWN_TYPE);

            Container = container;
        }

        public void Dispose()
        {
            if (Container != null)
            {
                Container.Dispose();
                Container = null;
            }
        }

        public IDrawerFileStuff LoadContentObject(IDrawerFile file)
        {
            var stuff = Container.Resolve<IDrawerFileStuff>(TASK_TYPE);
            
            LockerException ex;
            if (stuff.Load(file.Filename, out ex) && ex == null)
                return stuff;

            stuff = Container.Resolve<IDrawerFileStuff>(UNKNOWN_TYPE);
            if (stuff.Load(file.Filename, out ex) && ex == null)
                return stuff;

            return new UnknownFile();
        }

        public IDrawerFileStuff CreateDefaultContent()
        {
            return Container.Resolve<IDrawerFileStuff>(TASK_TYPE);
        }
    }
}
